<template>
  <div ref="treeBox" @click="aaa = '2'">
    <div>
      <el-row>
        <el-col :span="7">
          <el-card class="box-card">
            <el-input
              class="select_input"
              placeholder="输入关键字进行过滤"
              v-model="filterText"
            ></el-input>
            <!-- <abbr title="添加分组">
            <el-button class="u-add-parent" type="primary" icon="el-icon-plus" circle></el-button>
          </abbr>
          <abbr title="删除选中">
            <el-button class="u-delect-all" type="danger" icon="el-icon-delete" circle></el-button>
            </abbr>-->
            <el-tree
              :data="treeData"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
            >
              <div
                class="custom-tree-node"
                @click="routerConfig(data)"
                slot-scope="{ node, data }"
              >
                <div class="z-inline">{{ node.label }}</div>
                <div class="z-inline">
                  <el-popover
                    ref="popoverUpdate"
                    trigger="click"
                    placement="right"
                    title="移动节点"
                    width="600"
                    content
                  >
                    <div>
                      <el-form
                        :model="ruleFormUpdate"
                        :rules="rulesMoveForm"
                        :ref="'moveDom' + node.id"
                        label-width="100px"
                        class="demo-ruleForm"
                      >
                        <el-form-item label="节点目录" prop="parent">
                          <el-popover
                            placement="right"
                            width="400"
                            trigger="hover"
                          >
                            <el-tree
                              :data="treeDataCopy"
                              @node-click="handleNodeClick"
                            ></el-tree>
                            <a slot="reference">{{ moveForm.lable }}</a>
                          </el-popover>
                        </el-form-item>
                        <el-form-item>
                          <el-button
                            type="primary"
                            @click="moveDomNow('moveDom' + node.id)"
                            >确定</el-button
                          >
                          <el-button @click="close()">取消</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                    <el-button
                      slot="reference"
                      type="text"
                      size="mini"
                      @click.stop="() => moveDom(node, data)"
                      >移动</el-button
                    >
                  </el-popover>
                  <el-popover
                    ref="popoverAdd"
                    placement="bottom"
                    title="添加选项"
                    width="500"
                    trigger="click"
                  >
                    <div>
                      <el-form
                        :model="ruleFormAdd"
                        :rules="rulesAdd"
                        :ref="'addDom' + node.id"
                        label-width="100px"
                        class="demo-ruleForm"
                      >
                        <el-form-item label="节点名" prop="node_name">
                          <el-input v-model="ruleFormAdd.node_name"></el-input>
                        </el-form-item>
                        <el-form-item label="节点类型" prop="node_type">
                          <el-select
                            v-model="ruleFormAdd.node_type"
                            placeholder="请选择"
                          >
                            <el-option
                              v-for="item in typeArr"
                              :key="item.value"
                              :label="item.display_value"
                              :value="item.t_id"
                            ></el-option>
                          </el-select>
                          <!-- <el-input v-model=""></el-input> -->
                        </el-form-item>
                        <el-form-item label="节点值">
                          <el-input v-model="ruleFormAdd.node_value"></el-input>
                        </el-form-item>
                        <el-form-item>
                          <el-button
                            type="primary"
                            @click="appendUrl('addDom' + node.id)"
                            >添加</el-button
                          >
                          <el-button @click="close()">取消</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                    <el-button
                      slot="reference"
                      type="text"
                      size="mini"
                      @click.stop="() => append(data)"
                      >添加</el-button
                    >
                  </el-popover>
                  <el-popover
                    ref="popoverUpdate"
                    trigger="click"
                    placement="right"
                    title="修改选项"
                    width="500"
                    content
                  >
                    <div>
                      <el-form
                        :model="ruleFormUpdate"
                        :rules="rulesUpdate"
                        :ref="'updateDom' + node.id"
                        label-width="100px"
                        class="demo-ruleForm"
                      >
                        <el-form-item label="节点名" prop="node_name">
                          <el-input
                            v-model="ruleFormUpdate.node_name"
                          ></el-input>
                        </el-form-item>
                        <el-form-item label="节点类型" prop="node_type">
                          <el-select
                            v-model="ruleFormUpdate.node_type"
                            placeholder="请选择"
                          >
                            <el-option
                              v-for="item in typeArr"
                              :key="item.value"
                              :label="item.display_value"
                              :value="item.t_id"
                            ></el-option>
                          </el-select>
                          <!-- <el-input v-model=""></el-input> -->
                        </el-form-item>
                        <el-form-item label="节点值">
                          <el-input
                            v-model="ruleFormUpdate.node_value"
                          ></el-input>
                        </el-form-item>
                        <el-form-item>
                          <el-button
                            type="primary"
                            @click="updateUrl('updateDom' + node.id)"
                            >修改</el-button
                          >
                          <el-button @click="close()">取消</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                    <el-button
                      slot="reference"
                      type="text"
                      size="mini"
                      @click.stop="() => update(node, data)"
                      >修改</el-button
                    >
                  </el-popover>
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="() => remove(node, data)"
                    >删除</el-button
                  >
                </div>
              </div>
            </el-tree>
          </el-card>
        </el-col>
        <el-col :span="1" class="u-icon-box">
          &nbsp;
          <!-- <i class="el-icon-sort"></i> -->
        </el-col>
        <el-col :span="16" v-show="rowTableShow">
          <tableInTree
            ref="ol"
            v-if="tableShow"
            :vueNodeData="vueNodeData"
            @setFormData="setFormData"
            @routerConfigShowC="routerConfigShowC"
            :buttonTyoeArr="buttonTyoeArr"
          ></tableInTree>
        </el-col>

        <el-dialog
          :visible.sync="routerConfigShow"
          :close-on-click-modal="false"
          width="40%"
        >
          <h2>{{ ConfigDataTitle }}</h2>
          <div class="grid-content bg-purple-light">
            <!-- <el-dialog :title="routerConfigData.nodeName" :visible.sync="routerConfigShow" width="40%"> -->
            <el-form
              :model="routerConfigData"
              ref="routerConfigData"
              label-width="120px"
              class="demo-ruleForm"
            >
              <el-form-item label="页面资源名称">
                <el-input v-model="routerConfigData.page_name"></el-input>
              </el-form-item>
              <el-form-item label="按钮值">
                <el-input v-model="routerConfigData.btn_key"></el-input>
              </el-form-item>
              <el-form-item label="资源权限验证类">
                <el-input v-model="routerConfigData.handle_class"></el-input>
              </el-form-item>
              <el-form-item label="描述">
                <el-input v-model="routerConfigData.description"></el-input>
              </el-form-item>
              <el-form-item label="按钮类型">
                <el-select
                  v-model="routerConfigData.button_type"
                  placeholder="请选择按钮类型"
                >
                  <el-option
                    v-for="(item, index) in buttonTyoeArr"
                    :key="index"
                    :label="item.display_value"
                    :value="item.t_id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="路由名">
                <el-input v-model="routerConfigData.router_name"></el-input>
              </el-form-item>
              <el-form-item label="请求类型" prop>
                <el-select v-model="routerConfigData.request_type" placeholder="请选择">
                  <el-option
                    v-for="item in requestArr"
                    :key="item.value"
                    :label="item.display_value"
                    :value="item.t_id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="URL" prop="url">
                <el-input v-model="routerConfigData.url"></el-input>
              </el-form-item>
              <el-form-item label="前置处理器" prop>
                <el-input type="textarea" v-model="routerConfigData.pre_processors"></el-input>
              </el-form-item>
              <el-form-item label="数据处理器" prop>
                <el-input type="textarea" v-model="routerConfigData.data_processors"></el-input>
              </el-form-item>
              <el-form-item label="后置处理器" prop>
                <el-input type="textarea" v-model="routerConfigData.post_processors"></el-input>
              </el-form-item>
              <el-form-item label="bean定义" prop>
                <el-input type="textarea" v-model="routerConfigData.bean_definition"></el-input>
              </el-form-item>
              <el-form-item label="请求参数" prop>
                <el-input type="textarea" v-model="routerConfigData.request"></el-input>
              </el-form-item>
              <el-form-item label="接口响应" prop>
                <el-input type="textarea" v-model="routerConfigData.response"></el-input>
              </el-form-item>
              <el-form-item label="接口说明" prop>
                <el-input type="textarea" v-model="routerConfigData.description"></el-input>
              </el-form-item>
              <el-form-item label="接口负责人" prop>
                <el-input v-model="routerConfigData.principal"></el-input>
              </el-form-item>
              <el-form-item label="测试结果" prop>
                <el-input type="textarea" v-model="routerConfigData.testResult"></el-input>
              </el-form-item>-->
              <el-form-item>
                <div class="z-align-right">
                  <!-- <el-button class="u-test-interface" @click="testRequest">测 试</el-button> -->
                  <el-button @click="routerConfigShow = false">取 消</el-button>
                  <el-button
                    type="primary"
                    v-if="routerConfigVale == 'insert'"
                    @click="routerConfigUpdate('insert')"
                    >插 入</el-button
                  >
                  <el-button
                    type="primary"
                    v-else
                    @click="routerConfigUpdate('update')"
                    >修 改</el-button
                  >
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-dialog>
      </el-row>
    </div>
  </div>
</template>
<script>
import tableInTree from './table-in-Btn-tree';
import {
  // niceRouterManageTree,
  // tableInsert,
  // tableUpdate,
  addBtnTarget,
  findEnumTreeByMultiFieldIds,
  queyEnumByTableName,
  queryList,
  // addTarget,
  // updateRouterTreeNodeTarget,
  updateButtonTreeNodeTarget,
  // updateRouterTreeNode,
  moveButtonTreeNode,
  updateButtonTreeNode,
  deleteButtonTreeNode,
  // moveRouterTreeNode,
  getBtnTree,
  buttonTreeAddNode,
} from '@/api/api.js';
import { format } from '@/utils/index.js';
export default {
  components: { tableInTree },
  data() {
    return {
      tableShow: false,
      buttonTyoeArr: [],
      rowTableShow: false,
      ConfigDataTitle: '',
      node_in: {},
      data_in: {},
      rulesMoveForm: {
        // parent: [{ required: true, message: '请选择新节点', trigger: 'blur' }]
      },
      moveForm: {
        lable: '请选择',
        parent: '',
        moveId: '',
      },
      boxHeight: '0px',
      requestArr: [],
      routerConfigVale: 'insert',
      routerConfigData: {},
      routerConfigShow: false,
      typeArr: [],
      aaa: '',
      addDataSet: {},
      updateDataSet: {},
      filterText: '',
      treeData: [],
      treeDataCopy: [],
      ruleFormAdd: {
        node_name: '',
        node_type: '',
        node_value: '',
      },
      rulesAdd: {
        node_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur',
          },
        ],
        node_type: [
          { required: true, message: '请选择节点类型', trigger: 'change' },
        ],
      },
      ruleFormUpdate: {
        node_name: '',
        node_type: '',
        node_value: '',
      },
      rulesUpdate: {
        node_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur',
          },
        ],
        node_type: [
          { required: true, message: '请选择节点类型', trigger: 'change' },
        ],
      },
      vueNodeData: {
        node_id: 0,
      },
    };
  },
  created() {
    this.getTreeUrl();
    this.getSelectDAta();
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    setFormData(e) {
      console.log(e);
      this.routerConfigData = {
        node_id: this.vueNodeData.node_id,
        nodeName: this.vueNodeData.label,
        id: e.id,
        page_name: e.page_name,
        btn_key: e.btn_key,
        handle_class: e.handle_class,
        description: e.description,
        button_type: e.button_type,
      };
      this.ConfigDataTitle = '按钮详情';
      this.routerConfigVale = 'update';
      this.routerConfigShow = true;
    },
    routerConfigShowC(e) {
      this.routerConfigData = {
        node_id: this.vueNodeData.node_id,
        nodeName: this.vueNodeData.label,
        page_name: '',
        btn_key: '',
        handle_class: '',
        description: '',
        button_type: '',
        // router_name: '',
        // url: '', // url
        // id: '',
        // request_type: '', // 请求类型
        // description: '', // 接口说明
        // pre_processors: '', // 前置处理器
        // data_processors: '', // 数据处理器
        // post_processors: '', // 后置处理器
        // bean_definition: '',
        // principal: '', // 接口负责人
        // request: '',
        // response: '',
        // testResult: ''
      };
      this.ConfigDataTitle = '新建路由';
      this.routerConfigVale = 'insert';
      this.routerConfigShow = e;
    },
    // 测试接口
    testRequest() {
      let type;
      // routerConfigData.request_type
      this.requestArr.map((item) => {
        if (this.routerConfigData.request_type === item.t_id) {
          type = item.display_value.toLowerCase();
        }
      });
      let data = JSON.parse(this.routerConfigData.request);
      this.$http({
        url: this.$http.adornUrl(this.routerConfigData.url),
        method: type,
        data: this.$http.adornData(data),
      }).then(({ data }) => {
        this.$message({
          message: '测试结果已返回',
          type: 'success',
        });
        this.routerConfigData.testResult = format(JSON.stringify(data), false);
      });
    },
    // 移动目录交互请求
    async moveDomNow(e) {
      if (this.moveForm.parent) {
        // 修改接口
        let res = await moveButtonTreeNode({
          node_id: this.moveForm.moveId,
          parent: this.moveForm.parent,
        });
        if (res[0]) {
          return;
        }
        let dataCopy = JSON.parse(JSON.stringify(this.data_in));
        const parent = this.node_in.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(
          (d) => d.node_id === this.data_in.node_id
        );
        children.splice(index, 1);
        this.addDataSet.children.push(dataCopy);
        this.close();
      } else {
        this.$message('您未选择节点');
      }
    },
    // 移动目录选中节点
    handleNodeClick(e) {
      this.moveForm.lable = e.label;
      this.moveForm.parent = e.node_id;
      this.addDataSet = e;
    },
    // 配置移动数据
    moveDom(node, data) {
      this.moveForm.lable = '请选择';
      this.moveForm.parent = '';
      this.moveForm.moveId = data.node_id;
      this.node_in = node;
      this.data_in = data;
      this.treeDataCopy = this.treeData;
    },
    async routerConfigUpdate(e) {
      // 插入
      if (e === 'insert') {
        let res = await addBtnTarget({
          list: [
            {
              page_name: this.routerConfigData.page_name,
              btn_key: this.routerConfigData.btn_key,
              handle_class: this.routerConfigData.handle_class,
              description: this.routerConfigData.description,
              button_type: this.routerConfigData.button_type,
            },
          ],
          node_id: this.routerConfigData.node_id,
        });
        if (res[0]) {
          return;
        }
        this.$message({
          message: '插入成功',
          type: 'success',
        });
        this.routerConfigShow = false;
      } else {
        console.log(this.routerConfigData);
        // 修改
        let res = await updateButtonTreeNodeTarget([
          {
            table_name: 'nice_permission_page_btn',
            update: [
              {
                page_name: this.routerConfigData.page_name,
                btn_key: this.routerConfigData.btn_key,
                handle_class: this.routerConfigData.handle_class,
                description: this.routerConfigData.description,
                button_type: this.routerConfigData.button_type,
              },
            ],
            where: [
              {
                id: this.routerConfigData.id,
              },
            ],
          },
        ]);
        if (res[0]) {
          return;
        }
        this.$message({
          message: '已更新内容',
          type: 'success',
        });
      }
      this.$refs.ol.getTableList();
      // this.routerConfigShow = false
    },
    async routerConfig(e) {
      let typeValue;
      for (let i = 0; i < this.typeArr.length; i++) {
        if (e.node_type === this.typeArr[i].t_id) {
          typeValue = this.typeArr[i].display_value;
        }
      }
      if (typeValue === '节点详情表') {
        this.ConfigDataTitle = e.label;
        this.routerConfigData = {
          node_id: e.node_id,
          nodeName: e.label,
          url: '', // url
          request_type: '', // 请求类型
          description: '', // 接口说明
          pre_processors: '', // 前置处理器
          data_processors: '', // 数据处理器
          post_processors: '', // 后置处理器
          bean_definition: '',
          principal: '', // 接口负责人
          request: '',
          response: '',
          testResult: '',
          button_type: '',
        };
        this.routerConfigVale = 'insert';
        let res = await queryList({
          table_name: 'nice_router',
          node_id: this.routerConfigData.node_id,
        });
        if (res[1].data && res[1].data.length > 0) {
          this.routerConfigVale = 'update';
          let obj = res[1].data[0];
          this.routerConfigData.url = obj.url;
          this.routerConfigData.request_type = obj.request_type;
          this.routerConfigData.description = obj.description;
          this.routerConfigData.button_type = obj.button_type;
          this.routerConfigData.pre_processors = obj.pre_processors;
          this.routerConfigData.data_processors = obj.data_processors;
          this.routerConfigData.post_processors = obj.post_processors;
          this.routerConfigData.bean_definition = obj.bean_definition;
          this.routerConfigData.principal = obj.principal;
          this.routerConfigData.request = obj.request;
          this.routerConfigData.response = obj.response;
        }

        if (this.$refs.treeBox.offsetHeight >= 1000) {
          this.boxHeight = this.$refs.treeBox.offsetHeight / 2 - 350 + 'px';
        } else {
          this.boxHeight = '0px';
        }
        this.routerConfigShow = true;
      } else if (typeValue === '访问Vue页面') {
        this.vueNodeData = e;
        this.rowTableShow = true;
      } else {
        this.routerConfigShow = false;
        this.rowTableShow = false;
        this.$message('无操作节点');
      }
    },
    // 获取下拉菜单数据
    async getSelectDAta() {
      let res = await findEnumTreeByMultiFieldIds({ param: ['100255'] });
      if (res[0]) {
        return;
      }
      this.typeArr = res[1].data[0].child;
      let res2 = await queyEnumByTableName({ tableName: 'nice_router' });
      if (res2[0]) {
        return;
      }
      this.requestArr = res2[1].data[0].child;
      console.log(this.requestArr, 'this.requestArr');
      let res3 = await queyEnumByTableName({
        tableName: 'nice_permission_page_btn',
      });
      if (res3[0]) {
        return;
      }
      this.buttonTyoeArr = res3[1].data[0].child;
      this.tableShow = true;
    },
    close() {
      this.$refs.treeBox.click();
    },

    async getTreeUrl() {
      let res = await getBtnTree({
        id: 1,
      });
      if (res[0]) {
        return;
      }
      console.log(res[1], '11111');
      this.treeData = JSON.parse(
        JSON.stringify([res[1].data])
          .split('child')
          .join('children')
      );
      this.treeData = JSON.parse(
        JSON.stringify(this.treeData)
          .split('node_name')
          .join('label')
      );
      this.treeDataCopy = this.treeData;
      // console.log(this.data, '2222')
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 添加节点
    append(data) {
      this.routerConfigShow = false;
      this.addDataSet = data;
    },
    appendUrl(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const newChild = {
            label: this.ruleFormAdd.node_name,
            node_type: this.ruleFormAdd.node_type,
            node_value: this.ruleFormAdd.node_value,
            children: [],
          };
          // 添加接口
          let res = await buttonTreeAddNode({
            parent: this.addDataSet.node_id,
            node_name: this.ruleFormAdd.node_name,
            node_value: this.ruleFormAdd.node_value,
            node_type: this.ruleFormAdd.node_type,
          });
          if (res[0]) {
            return;
          }
          //
          newChild.node_id = res[1].data[0].list[0].id;
          if (!this.addDataSet.children) {
            this.$set(this.addDataSet, 'children', []);
          }
          this.addDataSet.children.push(newChild);
          this.close();
          this.ruleFormAdd = {
            node_name: '',
            node_type: '',
            node_value: '',
          };
          this.treeDataCopy = this.treeData;
        } else {
          // console.log()
          this.$message('输入的内容检测不合理');
          return false;
        }
      });
    },
    // 修改节点
    update(node, data) {
      this.routerConfigShow = false;
      this.updateDataSet = data;
      this.ruleFormUpdate = {
        node_name: data.label,
        node_type: data.node_type,
        node_value: data.node_value,
      };
    },
    // 修改请求
    updateUrl(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 修改接口
          let res = await updateButtonTreeNode({
            // table_name: 'nice_ol_router_tree',
            update: [
              {
                node_name: this.ruleFormUpdate.node_name,
                node_type: this.ruleFormUpdate.node_type,
                node_value: this.ruleFormUpdate.node_value,
              },
            ],
            where: [
              {
                node_id: this.updateDataSet.node_id,
              },
            ],
          });
          if (res[0]) {
            return;
          }
          //
          this.updateDataSet.label = this.ruleFormUpdate.node_name;
          this.updateDataSet.node_type = this.ruleFormUpdate.node_type;
          this.updateDataSet.node_value = this.ruleFormUpdate.node_value;
          // this.getTreeUrl()
          //
          this.close();
          this.ruleFormUpdate = {
            node_name: '',
            node_type: '',
            node_value: '',
          };
        } else {
          this.$message('输入的内容检测不合理');
          return false;
        }
      });
    },
    // 选择
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    remove(node, data) {
      this.routerConfigShow = false;
      this.$confirm('确认要删除？')
        .then(async (_) => {
          let res = await deleteButtonTreeNode({
            node_id: data.node_id,
          });
          if (res[0]) {
            return;
          }
          // this.getTreeUrl()
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex((d) => d.node_id === data.node_id);
          children.splice(index, 1);
        })
        .catch((_) => {});
    },
  },
};
</script>
<style scoped>
.select_input {
  margin-bottom: 10px;
}
.u-add-parent {
  transform: scale(0.7);
}
.u-delect-all {
  margin-left: -10px;
  transform: scale(0.7);
}
.z-inline {
  line-height: 40px;
}
.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.u-icon-box {
  text-align: center;
}
.el-icon-sort {
  /* margin-top: 55px; */
  font-size: 30px;
  transform: rotate(90deg);
}
.box-card {
  /* height: 78vh; */
  /* overflow: auto; */
}
.z-align-right {
  text-align: right;
}
.u-test-interface {
  float: left;
}
</style>
